package com.dcits.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;

import org.apache.commons.net.telnet.TelnetClient;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcits.business.report.AnalyzeInfoData;
import com.dcits.business.report.AnalyzeItemData;
import com.dcits.tool.excel.ExcelUtil;
import com.jfinal.kit.PathKit;

public class RmpUtil {
	private static final Logger logger = Logger.getLogger(RmpUtil.class);
	
	public static final String DATA_FILE_SAVE_PATH = "files" + File.separator;
	public static final String EXPORT_EXCEL_FILE_PATH = "exportExcel" + File.separator;
	
	
	public static final String DEFAULT_DATE_PATTERN = "HH:mm:ss"; 
	public static final String FULL_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
	
	public static final Map<String, String> apiTypeMark = new HashMap<String, String>();
	
	static {
		apiTypeMark.put("applicationResources", "应用资源数据");
		apiTypeMark.put("databaseResources", "数据库资源数据");
		apiTypeMark.put("clusterResources", "集群资源数据");
	}
	
	
	
	
	public static void main(String[] args) throws SocketException, IOException {
		TelnetClient client = new TelnetClient();
		client.connect("192.168.31.133", 20880);
		PrintStream out = new PrintStream(client.getOutputStream());
		//out.println(" ");
		out.println("status -l");
		out.flush();
		char lastChar = '>';
		StringBuffer sb = new StringBuffer(); 
		InputStream in = client.getInputStream();
		char ch = (char) in.read(); 
		while (true) {  
			 sb.append(ch);
			 if (ch == lastChar) {  
                 if (sb.toString().endsWith("dubbo>")) {  
                     System.out.println(sb.toString());; 
                     break;
                 }  
             } 
			 ch = (char) in.read(); 
		}
		client.disconnect();
	}
	
	 /**
     * 导出历史信息到excel文档
     * @param analyzeInfoDatas
     * @param valueKind 可选类型 最大值、最小值、平均值,目前只做平均值
     * @return
     */
    public static String ExportInfoData(Map<String, List<AnalyzeInfoData>> analyzeInfoDatas, JSONArray valueKind, String rootPath) throws Exception {
    	
    	String path = EXPORT_EXCEL_FILE_PATH;
		OutputStream outputStream = null; 
		String fileName = "result_" + System.currentTimeMillis() + ".xlsx";
		path = path + fileName;
    	
		try {
			//创建excel
			Workbook wb = ExcelUtil.createWorkBook(ExcelUtil.XLSX);
			Sheet sheet = ExcelUtil.createSheet(wb, "分析结果");
			
			CellStyle headerStyle = ExcelUtil.createHeadCellStyle(wb);
			String[] titles = new String[]{"HOST", "类型", "标签", "开始时间", "结束时间"};
			
			int rowNum = 0;
			for (Entry<String, List<AnalyzeInfoData>> entry:analyzeInfoDatas.entrySet()) {
				//写入标题
				Row titleRow = sheet.createRow(rowNum);
				
				for (int i = 0;i < titles.length;i ++) {
					Cell cell = titleRow.createCell(i);
					cell.setCellValue(titles[i]);
					cell.setCellStyle(headerStyle);
				}
				
				int cellNum = titles.length;
				int m = 1;
				for (AnalyzeInfoData aid:entry.getValue()) {
					int n = 0;
					Row row = sheet.createRow(rowNum + m);
					for (AnalyzeItemData itemData:aid.getItems()) {
						if (m == 1) {
							//继续写表头
							Cell cell = titleRow.createCell(cellNum + n);
							cell.setCellValue(itemData.getItemMark());
							cell.setCellStyle(headerStyle);
						}
						//写类别信息
						row.createCell(5 + n).setCellValue(itemData.getAvgValue());
						n ++;
					}
					//写基本信息
					row.createCell(0).setCellValue(aid.getHost());
					row.createCell(1).setCellValue(aid.getServerType());
					row.createCell(2).setCellValue(aid.getTags());
					row.createCell(3).setCellValue(aid.getBeginTime());
					row.createCell(4).setCellValue(aid.getEndTime());
					m++;
				}
				//每个类型表之间空3行
				rowNum += 3;
			}
			
			outputStream = new FileOutputStream(new File(rootPath + "/" + path));
			
			wb.write(outputStream);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("写excel文件失败：" + path, e);
			throw e;
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
		
    	return path;
    }
	
	
	/**
	 * 格式化日期
	 * @param date
	 * @param format
	 * @return
	 */
	public static String dataFormat(Date date, String format) {
		DateFormat dateFormat = new SimpleDateFormat(format); 
		return dateFormat.format(date);
	}
	
	/**
	 * 当前日期的String返回
	 * @return
	 */
	public static String getCurrentTime(String format) {
		return dataFormat(new Date(), format);
	}	
	
	
	/**
	 * jmx获取属性参数
	 * 
	 * @param objectName
	 * @param name
	 * @param connection
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getAttribute(ObjectName objectName, String name, MBeanServerConnection connection) {
	    Object obj = null;
	    try {
	        obj = connection.getAttribute(objectName, name);
	    } catch (Exception e) {
	        // TODO
	        e.printStackTrace();
	    }
	    return (T) obj;
	}
	
	/**
	 * 日期格式转换
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatDate(Date date, String format) {
	    DateFormat df = new SimpleDateFormat(format);
	    return df.format(date);
	}
	
	public static Date parseStrToDate(String date) {
		return parseStrToDate(date, FULL_DATE_PATTERN);
	}
	
	public static Date parseStrToDate(String date, String format) {
		DateFormat df = new SimpleDateFormat(format);
		try {
			return df.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}
	
	
	
	
	/**
	 * 字节转换成MB
	 * 
	 * @param bytes
	 * @return
	 */
	public static String byteToMB(long bytes) {
	    double mb = (double) bytes / 1024 / 1024;
	    DecimalFormat df = new DecimalFormat("0.00");
	    return df.format(mb);
	}
	
	/**
	 * 字节转换成KB
	 * 
	 * @param bytes
	 * @return
	 */
	public static String byteToKB(long bytes) {
	    double mb = (double) bytes / 1024;
	    DecimalFormat df = new DecimalFormat("0.00");
	    return df.format(mb);
	}
	
	/**
	 * 格式化时间长度
	 * @param span
	 * @return
	 */
	@SuppressWarnings("resource")
	public static String formatTimeSpan(long span) {  
        long minseconds = span % 1000;  
  
        span = span / 1000;  
        long seconds = span % 60;  
  
        span = span / 60;  
        long mins = span % 60;  
  
        span = span / 60;  
        long hours = span % 24;  
  
        span = span / 24;  
        long days = span;  
        return (new Formatter()).format("%1$d天 %2$02d:%3$02d:%4$02d.%5$03d",  
                days, hours, mins, seconds, minseconds).toString();  
    }
	/**
	 * 执行本地命令
	 * @param command
	 * @return
	 * @throws Exception 
	 */
	public static String execCommand(String command) throws Exception {
		BufferedReader br = null;
		StringBuilder returnStr = new StringBuilder();
		long begin = System.currentTimeMillis();
		try {
			ProcessBuilder pb = new ProcessBuilder();	
			pb.redirectErrorStream(true);			
			
			List<String> list = new ArrayList<>();
			list.addAll(Arrays.asList(command.split("\\s+")));
			
			Process p = pb.command(list).start();
			
			br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			
			String line = null;
			while ((line = br.readLine()) != null) {
				returnStr.append(line + "\n");
			}	
		} catch (Exception e) {
			throw e;
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		long end = System.currentTimeMillis();
		logger.debug("\n执行本地命令[" + command + "]耗时" + (end - begin) + "ms！");
		return returnStr.toString();
	}
	
	/**
	 * 生成excel保存非功能需求的测试数据
	 * @param apiData 全局数据
	 * @param apiMark 备注中文注释
	 * @return
	 */
	public static String exportApiDataToExcel(String apiData, String apiMark, String apiName) throws Exception {
		JSONObject apiDataObject = JSONObject.parseObject(apiData);
		JSONObject apiMarkObject = JSONObject.parseObject(apiMark);
		
		//创建excel
		OutputStream outputStream = null; 
		if (StringUtils.isEmpty(apiName)) {
			apiName = UUID.randomUUID().toString().replaceAll("-", "");
		}
		String path = EXPORT_EXCEL_FILE_PATH + apiName + ".xlsx";
		
		try {
			//创建excel
			Workbook wb = ExcelUtil.createWorkBook(ExcelUtil.XLSX);
			CellStyle headerStyle = ExcelUtil.createHeadCellStyle(wb);

			for (String typeKey:apiDataObject.keySet()) {
				createApiDataSheet(ExcelUtil.createSheet(wb, StringUtils.isEmpty(apiTypeMark.get(typeKey)) ? typeKey : apiTypeMark.get(typeKey))
						, apiDataObject.getJSONArray(typeKey)
						, apiMarkObject.getJSONObject(typeKey), headerStyle);				
			}
			
			outputStream = new FileOutputStream(new File(PathKit.getWebRootPath() + File.separator + path));
			
			wb.write(outputStream);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("创建文件" + path + "失败!", e);
			throw e;
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
		
		
		return path;
	}
	
	/**
	 * 创建生成apiData的sheet页内容
	 * @param sheet
	 * @param typeServerList
	 * @param typeMark
	 * @param headerStyle
	 */
	private static void createApiDataSheet(Sheet sheet, JSONArray typeServerList, JSONObject typeMark, CellStyle headerStyle) {
		int rownum = 0;
		for (Object o:typeServerList) {
			Row titleRow = null;
			if (rownum == 0) {
				titleRow = sheet.createRow(rownum++);
			}
			Row infoRow = sheet.createRow(rownum++);
			JSONObject serverInfo = (JSONObject) o;
			int cellNum = 0;
			for (String key:typeMark.keySet()) {				
				JSONObject mark = typeMark.getJSONObject(key);
				if (titleRow != null) {
					//创建表头
					Cell titleCell = titleRow.createCell(cellNum);
					titleCell.setCellStyle(headerStyle);
					titleCell.setCellValue(mark.getString("mark"));
				}
				infoRow.createCell(cellNum).setCellValue(StringUtils.isEmpty(serverInfo.getString(key)) ? "" : serverInfo.getString(key));	
				cellNum++;
			}
			titleRow = null;
		}
	}	
}
